package org.dant.ant.extension.types;

import java.io.*;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.DataType;

public class Expect extends DataType implements Serializable {

  protected boolean errstream = false;
  protected boolean empty = false;
  protected boolean exact = false;
  protected boolean negativematch = false;
  protected boolean erroronfail = false;

  protected File file = null;
  protected File dir = null;
  protected String text = null;
  
  public void setStream(String stream) {
    if ("err".equalsIgnoreCase(stream)) {
      errstream = true;
    } else if ("out".equalsIgnoreCase(stream)) {
      errstream = false;
    } else {
      throw new BuildException("Invalid Streamtype: only \"out\" and \"err\" allowed!");
    }
  }

  public void setEmpty(boolean e) {
    this.empty = e;
  }

  public void setFile(String f) {
    if (f == null) {
      return;
    }
    if (dir == null) {
      file = new File(f);
    } else {
      file = concatFiles(dir, f);
    }
//     if (f.equals("core")) {
//       saveExistingFile(file);
//     } else {
//       deleteExistingFile(file);
//     }
  }

  public void setDir(File d) {
    if (d == null) {
      return;
    }
    dir = d;
    if (file != null) {
      file = concatFiles(dir, file.toString());
      
//       if (file.getName().equals("core")) {
//         saveExistingFile(file);
//       } else {
//         deleteExistingFile(file);
//       }
    }
  }
  
  public void addText(String txt) {
    text = getProject().replaceProperties(txt);
  }
  
  public boolean isErrStream() {
    return this.errstream;
  }

  public File getFile() {
    return this.file;
  }

  public String getText() {
    return this.text;
  }

//   public String getOutStream() {
//     return stdout.toString();
//   }

//   public String getErrStream() {
//     return stderr.toString();
//   }

  protected static File concatFiles(File dir, String filename) {
    try {
      return new File(dir, filename).getCanonicalFile();
    } catch (IOException ioe) {
      return new File(dir, filename).getAbsoluteFile();
    }
  }

  public String toString() {
    StringBuffer sb = new StringBuffer();
    if (getFile() == null) {
      sb.append("expect ");
      if (errstream)
        sb.append(" stderr ");
      else
        sb.append(" stdout ");
      sb.append("stream: ");
      sb.append(getText());
      sb.append("\n");
    } else {
      sb.append("expect file: ");
      sb.append(getFile().toString());
    }
    return sb.toString();
  }
}
